<?php

namespace app\modules\backend\controllers;

use Yii;
use app\tools\Re;
use app\models\Banner;

class BannerController extends BaseController
{
    //轮播图列表
    public function actionBannerList(){
      $page = Yii::$app->request->post('page', 0);
      $page_size = Yii::$app->request->post('page_size', 20);
      $query = Banner::find()->where(['status' => [0,1]]);
      $banner_list = $query->orderBy('sort desc, created_at desc')->limit($page_size)->offset($page_size*$page)->all();
      $banner_data = [];
      if ($banner_list) {
        foreach ($banner_list as $v) {
          $banner_data[] = [
            'id' => $v->id,
            'cover' => $v->cover,
            'good_id' => $v->good_id,
            'good_name' => $v->good_id ? $v->good->name : '',
            'sort' => $v->sort,
            'status' => $v->status,
            'status_name' => $v->status == 1 ? '启用' : '禁用',
            'created_time' => date("Y-m-d H:i", $v->created_at)
          ];
        }
      }
      return Re::data([
        'data' => $banner_data,
        'totalPage' => $query->count(),
        'currentPage' => $page,
        'perPage' => $page_size
      ]);
    }

    //编辑轮播图
    public function actionEditBanner(){
      $id = Yii::$app->request->post('id', 0);
      $post = Yii::$app->request->post();
      return $this->edit(Banner::class, $id, $post);
    }

    //编辑轮播图状态
    public function actionChangeBannerStatus(){
      $id = Yii::$app->request->post('id', 0);
      $status = Yii::$app->request->post('status', 0);
      $banner = Banner::findOne($id);
      if (!$banner) {
        return Re::data(null, '轮播图信息读取失败', Re::ERROR);
      }
      $banner->status = $status;
      $banner->save();
      return Re::data();
    }
}
